# -*- coding: utf-8 -*-
import os
import shutil
import unittest

from common.config import Config
from utils import BSTestRunner, HTMLTestRunner, HTMLTestRunner2
from utils.log import Log

logger = Log()


def get_test_case():
    logger.info("构建测试用例开始")
    suites = unittest.defaultTestLoader.discover(Config.PATH_TESTCASE, top_level_dir=Config.PATH_TESTCASE)
    suitesList = []
    for suite in suites:
        suitesList.append(suite)
    logger.info("构建测试用例完毕")
    return tuple(suitesList)


# 每个进程运行方法
def run(suite):
    runner = HTMLTestRunner2.HTMLTestRunner(
        report=False  # 默认不输出报告，测试计划执行完后再重制报告并输出报告
    )
    result = runner.run(suite)
    return result


# 报告信息类
class ReMakeReport:
    startTime = " "
    stopTime = " "
    success_count = 0
    failure_count = 0
    error_count = 0
    title = " "
    description = " "
    test_method_results = []  # 元素为每个测试方法的执行结果
    test_plan_results = []  # 元素为每个测试计划的执行结果


# 写报告
def write_report(results: list) -> str:
    """
        与业务逻辑代码无关，可以不看
    """
    total_success_count = 0
    total_failure_count = 0
    total_error_count = 0
    total_results = []
    test_plan_results = results
    for i, result in enumerate(results):
        total_success_count += result.success_count
        total_failure_count += result.failure_count
        total_error_count += result.error_count
        total_results.extend(result.result)
    ReMakeReport.startTime = result.startTime
    ReMakeReport.stopTime = result.stopTime
    ReMakeReport.success_count = total_success_count
    ReMakeReport.failure_count = total_failure_count
    ReMakeReport.error_count = total_error_count
    ReMakeReport.title = Config.REPORT_TITLE
    ReMakeReport.description = Config.REPORT_DESCRIPTION
    ReMakeReport.test_method_results = total_results
    ReMakeReport.test_plan_results = test_plan_results
    # 报告相关信息
    report_dir = Config.PATH_REPORT
    report_file_path = Config.FILE_PATH_REPORT
    logger.info("开始生成测试报告:" + report_file_path)
    os.mkdir(report_dir)
    reportimgdir = report_dir + "\\img"
    tempimgdir = Config.PATH_REPORT_SCREENSHOT
    with open(report_file_path, "wb") as fp:
        htmlTestRunner = HTMLTestRunner2.HTMLTestRunner(stream=fp, title=Config.REPORT_TITLE,
                                                        description=Config.REPORT_DESCRIPTION)
        htmlTestRunner.startTime = ReMakeReport.startTime
        htmlTestRunner.stopTime = ReMakeReport.stopTime
        htmlTestRunner.title = ReMakeReport.title
        htmlTestRunner.description = ReMakeReport.description
        htmlTestRunner.generateReport(test=None, result=ReMakeReport)
    # 将css 和 js　拷贝到测试报告目录下面
    src_css = os.path.join(Config.PATH_RESOURCES, "bootstrap.min.css")
    src_js = os.path.join(Config.PATH_RESOURCES, "echarts.common.min.js")
    shutil.copy2(src=src_css, dst=report_dir)
    shutil.copy2(src=src_js, dst=report_dir)
    # 将截图拷贝到测试报告目录下面并清空temp目录
    shutil.copytree(tempimgdir, reportimgdir)
    shutil.rmtree(tempimgdir)


def init():
    """检查temp目录是否存在，存在时，清空文件，不存在时创建"""
    tempimg_dir = Config.PATH_REPORT_SCREENSHOT
    if os.path.exists(tempimg_dir):
        shutil.rmtree(tempimg_dir)
        os.mkdir(tempimg_dir)
    else:
        os.mkdir(tempimg_dir)


def main():
    """
    收集测试用例，执行测试用例和生成测试报告
    """
    init()
    allsuites = get_test_case()
    logger.info("测试执行开始")
    # 收集测试用例日志信息
    results = []
    for suites in allsuites:
        rl = run(suites)
        results.append(rl)
    logger.info("测试执行结束")
    # 生成测试报告
    write_report(results)


if __name__ == '__main__':
    main()
